//
//  ST_GiftOfGuideController.swift
//  btvideo
//
//  Created by mac on 2020/10/21.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import RxCocoa
import RxSwift

/**
 送守护专用
 */
class ST_GiftOfGuideController: UIViewController,ST_TIANPaymentTransactionStateDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()
        
         
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(16)
            make.height.equalTo(gift_container_height+58+71+16+BTSafeAreaBottom)
        }
        
        view.addSubview(close_view)
        close_view.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(root_view.snp.top)
        }
        
        root_view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(15)
            make.height.equalTo(22)
        }
        
        
        root_view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(58)
            make.height.equalTo(gift_container_height+10)
        }
        
        root_view.addSubview(pageControl)
        
        pageControl.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(collectionView.snp.bottom).offset(1)
            make.height.equalTo(5+10)
        }
        
        
        root_view.addSubview(giveBtn)
        root_view.addSubview(recharge_btn)
        giveBtn.snp.makeConstraints { (make) in
            make.width.equalTo(78)
            make.height.equalTo(34)
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-10-16)
            make.right.equalToSuperview().offset(-15)
        }
        
        recharge_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(giveBtn)
            make.left.equalToSuperview().offset(15)
        }
        
        create_supplement_container_view()
        
        binding()
        
    }
    
    var disposeBag = DisposeBag()
    
    fileprivate var lastPage = 0
    
    fileprivate func binding(){
        
        viewModel.fetchGiftListSession().subscribe(onNext: {[weak self] result in
            
            switch result {
            case .success:
                
                self?.pull_succeed()
                
            case .failure(let err):
                self?.toast(text: err.e)
            }
            
        }).disposed(by: disposeBag)
        
    }
    
    
    fileprivate func pull_succeed(){
        
        
        last_selected_control_model = viewModel.selectFirstGuideGift()
        
        collectionView.reloadData()
        
        if let first = viewModel.dataArrayForGuide.first{
            
            pageControl.numberOfPages = first.pages
            pageControl.currentPage = 0
            
            pageControl.isHidden = pageControl.numberOfPages < 2
        }
        
    }
    
    fileprivate func create_supplement_container_view(){
        
        self.view.addSubview(supplement_container_view)
        supplement_container_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(155)
            make.bottom.equalTo(root_view.snp.top).offset( iPhoneXSeries ? -40 : -20)
            make.centerX.equalToSuperview()
        }
        
        supplement_container_view.addSubview(icon)
        icon.snp.makeConstraints { (make) in
            make.width.height.equalTo(115)
            make.center.equalToSuperview()
        }
        
        supplement_container_view.addSubview(icon_supplement_image_view)
        icon_supplement_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
    }
    
//    MARK:- properties
    fileprivate lazy var icon:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.cornerRadius = 115/2.0
        control.imageView?.contentMode = .scaleAspectFill
        control.clipsToBounds = true
        return control
    }()
    
    fileprivate lazy var icon_supplement_image_view:UIImageView = {
        let control = UIImageView()
       return control
    }()
    
    fileprivate lazy var supplement_container_view:UIView = {
        let control = UIImageView()
        control.alpha = 0
       return control
    }()
    
    
    
    fileprivate lazy var root_view:UIView = {
       let control = UIView()
        control.backgroundColor = UIColor.init(hex: 0x202223)
        control.cornerRadius = 16
        return control
    }()
    
    fileprivate lazy var close_view:UIButton = {
       let control = UIButton()
        control.addTarget(self, action: #selector(closeHanlde), for: UIControl.Event.touchUpInside)
        return control
    }()
    @objc fileprivate func closeHanlde(){
        
        last_selected_control_model?.isSelected = false
        
        self.goback_previous_controller()
    }
    
    fileprivate lazy var gift_container_height = ST_GiftItemView.height*2+ST_GiftItemView.gap

    fileprivate lazy var layout:UICollectionViewFlowLayout = {
      let controlLayout = UICollectionViewFlowLayout()
        controlLayout.scrollDirection = .horizontal
        controlLayout.minimumLineSpacing = 0
        controlLayout.minimumInteritemSpacing = 0
        controlLayout.itemSize = CGSize.init(width: ScreenWidth, height: gift_container_height)
       return controlLayout
   }()
       
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "送她守护头像框"
        control.textColor = UIColor.white
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.isPagingEnabled = true
        control.backgroundColor = Color.clear
        control.delegate = self
        control.dataSource = self
//        control.alwaysBounceVertical = true
        
        control.register(cellWithClass: ST_GiftTabCell.self)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
    
    fileprivate weak var last_selected_control_model:ST_BTGiftModel?{
        didSet{
            
            guard let m = last_selected_control_model else{
                self.supplement_container_view.alpha = 0
                return
            }
            
            if m.tabType == .sweetGuard{
                
                self.supplement_container_view.alpha = 1
                
                self.icon_supplement_image_view.pin_setImage(from: m.imageUrl.url)
                
            }else{
                self.supplement_container_view.alpha = 0
            }
            
        }
    }
    
    fileprivate lazy var viewModel = ST_GiftViewModel()
       
    fileprivate lazy var pageControl:UIPageControl = {
        let control = UIPageControl()
        control.pageIndicatorTintColor = UIColor.init(hex: 0xACB4C0)
        control.currentPageIndicatorTintColor = UIColor.init(hex: 0xFEC207)
//        control.addTarget(self, action: #selector(changePage(sender:)
//            ), for: UIControl.Event.touchUpInside)
        control.isUserInteractionEnabled = false
        return control
    }()
    
    fileprivate lazy var giveBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("赠送")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.setTitleColorForAllStates(UIColor.init(hex: 0x202223)!)
        control.cornerRadius = 17
        control.addTarget(self, action: #selector(give_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var recharge_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.setTitleForAllStates("马上充值")
        control.setTitleColorForAllStates(Color.init(hexString: "#FEC207")!)
        
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_icon_下一页_orange")!)
        
        control.semanticContentAttribute = .forceRightToLeft
        control.addTarget(self, action: #selector(recharge_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate var give_member:BTMemberGoodsModel?
    
    var present_goods_closure:((ST_BTIMGiftMessageModel)->())?
    
    var userId = ""
    
    var avatar = ""{
        didSet{
            icon.pin_setImage(from: avatar.url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        }
    }
}

extension ST_GiftOfGuideController{
    
    func transaction_succeed() {
        
        guard let memberModel = self.give_member else { return }
        
        let goods = ST_BTIMGiftMessageModel()
        
        goods.goodsId = memberModel.limited_time.string
        
        goods.title = "送了你\(memberModel.limited_time)个月会员"
        
        goods.type = ST_IMGoodsType.give_member
      
        goods.subTitle = "亲密度+"+memberModel.intimacy.string
        
        present_goods_closure?(goods)
        
        let vc = BTVerticalAlertViewController.createGiveMemberAlert()
        
        GlobalPresent(toController: vc)
    }
    
    @objc fileprivate func recharge_handle(){
        
        ST_RechargeViewController.toast()
        
    }
    
    @objc fileprivate func recharge_tips_handle(){
        
        
//        let alert = BTVerticalAlertViewController.createRequireRechargeAlert()
//
//        alert.confirm_closure = {[weak self] in
//
//            self?.recharge_handle()
//        }
//
//        GlobalPresent(toController: alert)
        
        ST_RechargeViewController.toast()
        
        self.hidden_indeterminate_h_u_d()
    }
    
    @objc fileprivate func give_handle(){
        
        
        
        guard let model = last_selected_control_model else { return  }
        
        
        self.show_indeterminate_h_u_d()
        
        if model.tabType == .member{
            
            
            guard let memberModel = model.give_member else {
                self.hidden_indeterminate_h_u_d()
                return
            }
            
            self.give_member = memberModel
            
            ST_MaidWayManager.shared.source = .聊天赠送
            
            ST_MaidWayManager.shared.doWay(id: memberModel.id.string, giveId: self.userId, delegate: self)
            
        }else{
           
            guard let goodsModel = model.common ,let coin = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sweet_coin else {
                self.hidden_indeterminate_h_u_d()
                return
            }
            
            let api = goodsModel.type == GoodsType.gift ?  PH.presentSmallGiftApi : PH.presentGuardSupplementApi
            
            
            if coin < goodsModel.useCoin.float{
                
                
                if goodsModel.type == GoodsType.gift{
                    ST_MaidWayManager.shared.source = .送礼物
                }else{
                    ST_MaidWayManager.shared.source = .送守护
                }
                
                recharge_tips_handle()
                
                return
            }
            
            JVrequest(api,parameters: ["target_accid":self.userId,"id":goodsModel.id ?? ""], success: { (json) in
                
                
                self.toast(text: "赠送成功")
                
                main_thread_execute {
                    ST_BTUserInfoManager.shared.modify_sweet_coin(value: coin - goodsModel.useCoin.float)
                    ST_BTUserInfoManager.shared.refresh_my_sweetheart_list()
                }
                
                
                
                let goods = ST_BTIMGiftMessageModel()
                
                goods.goodsId = goodsModel.id.string
                goods.svgaUrl = model.svgaUrl
                if goodsModel.type == GoodsType.gift{
                    goods.title = "送你1个" + goodsModel.name
                    goods.type = ST_IMGoodsType.gift
                }else{
                    goods.title = goodsModel.name + "守护了你"
                    goods.type = ST_IMGoodsType.sweetGuard
                    
                    let eDate = Date().adding(Calendar.Component.day, value: 1)
                    
                    var userInfoDict = ["guardTime":eDate.timeIntervalSince1970.int,    "guardContent":model.imageUrl,"userId":self.userId,"effectiveTime":goodsModel.effectiveTime ?? 0] as [String : Any]
                  
                    let sortedArray = self.viewModel.dataArrayForGuide.first?.pageArray.sorted(by: { (img0: ST_BTGiftModel, img1: ST_BTGiftModel) -> Bool in
                        return img0.common?.useCoin ?? 0 < img1.common?.useCoin ?? 0
                    })
                    
                    let nextElement = sortedArray?.first(where: { (kk) -> Bool in
                        return kk.common?.useCoin ?? 0 > goodsModel.useCoin
                    })
                    
                    
                    
                    if let next = nextElement{
                        userInfoDict.updateValue(next.common?.useCoin ?? 0, forKey: "guard_next_coin")
                    }else{
                        userInfoDict.updateValue(true, forKey: "guard_is_max")
                    }
                    
                    NotificationCenter.default.post(name: Notification.Name.sendGuard, object: nil, userInfo: userInfoDict)
                    
                }
                goods.subTitle = "亲密度+"+goodsModel.intimacy.string
                
                goods.imageUrl = model.imageUrl
                
                self.present_goods_closure?(goods)
                
                
            }) { (code, err) in
                
                self.hidden_indeterminate_h_u_d()
                
                if code == 30002{
                    
                    let alert = BTVerticalAlertViewController.createGuardAlert(title: "无法对TA守护哦", content: "她已经有人使用最高级的守护了哦~\n要不再去看看其他人吧")
                    
                    GlobalPresent(toController: alert)
                    
                }else if code == 30001{
                    
                    let alert = BTVerticalAlertViewController.createGuardAlert(title: "需要更高级的守护", content: "TA已经有人守护了哦~使用更高级的守护你\n就可以顶掉那个人，成为TA的专属守护者")
                    
                    GlobalPresent(toController: alert)
                    
                }else{
                    self.toast(text: err)
                }
                
                
            }
        }
        
        
        
    }
    @objc fileprivate func changePage(sender:UIPageControl){
        
        print("点击跳转页事件")
    }
    
    fileprivate func update_selected(item:ST_BTGiftModel){
        
        if item == last_selected_control_model{
            return
        }
        
        last_selected_control_model?.isSelected = false
        last_selected_control_model = item
        
        collectionView.reloadItems(at: collectionView.indexPathsForVisibleItems)
    }
    /// 滑动到下一页
    fileprivate func scrollTo(currPage:Int){
        
        guard currPage > -1,let m = viewModel.dataArrayForGuide[safe:currPage],lastPage != currPage else{
            return
        }
            
        lastPage = currPage
        
        if let firstItem = m.pageArray.first{
            m.pageArray.first?.isSelected = true
            self.update_selected(item: firstItem)
        }
        
        self.recharge_btn.isHidden = m.indexOfTab == 2
        self.pageControl.numberOfPages = m.pages
        self.pageControl.currentPage = m.currentPageOfTab
        self.pageControl.isHidden = self.pageControl.numberOfPages < 2
        
        
    }
    
}


extension ST_GiftOfGuideController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewModel.dataArrayForGuide.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let model = viewModel.dataArrayForGuide[indexPath.row]
     
        let cell = collectionView.dequeueReusableCell(withClass: ST_GiftTabCell.self, for: indexPath)
        
        cell.model = model
        
        cell.selected_closure = {[weak self] model in
            
            self?.last_selected_control_model?.isSelected = false
            self?.last_selected_control_model = model
            self?.collectionView.reloadData()
        }
        
        return cell
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
            
        
        if !decelerate{
                scrollviewdidEndScroll(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
            scrollviewdidEndScroll(scrollView)
        
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        

        let currPage = (scrollView.contentOffset.x/ScreenWidth).int
        
        scrollTo(currPage: currPage)
    }
    
//    MARK: 停止滚动
    func scrollviewdidEndScroll(_ scrollView:UIScrollView){
        
        let currPage = (scrollView.contentOffset.x/ScreenWidth).int
        
        scrollTo(currPage: currPage)
        
    }
    
    
    
}
